
#if 1
#include "Thread.hpp"
#include "CurrentThread.hpp"
#include <semaphore.h>


namespace zephyr {

std::atomic_int Thread::m_numCreated{0};

Thread::Thread(ThreadFuc cb, const std::string &name)
    : m_started(false)
    , m_joined(false)
    , m_tid(0)
    , m_func(std::move(cb))
    , m_name(name) {
    setDefauleName();
}

Thread::~Thread() {
    if (m_started && !m_joined) {
        m_thread->detach();
    }
}

void Thread::start() {
    m_started = true;
    sem_t sem;
    sem_init(&sem, false, 0);

    m_thread = std::make_shared<std::thread>(
        [&]() {
            m_tid = CurrentThread::tid();
            sem_post(&sem);
            m_func();
        }
    );
    sem_wait(&sem);
}

void Thread::join() {
    m_joined = true;
    m_thread->join();
}

void Thread::setDefauleName() {
    int num = ++m_numCreated;
    if (m_name.empty()) {
        char buf[32] = {0};
        snprintf(buf, sizeof(buf), "Thread%d", num);
        m_name = buf;
    }
}

}
#endif